class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *q = head, *p = head;
        while(q && q->next){
            q = q->next->next;
            p = p->next;
            if(q == p) break;
        }
        if(q == NULL || q->next == NULL) return NULL;
        p = head;
        while(q != p) p = p->next, q = q->next;
        return p;
    }
};